package migrate

import (
	"context"

	"gitee.com/linxing_3/sr-core/app"
	"gitee.com/linxing_3/sr-core/config/source"
	"gitee.com/linxing_3/sr-core/plugins/log"
	"gitee.com/linxing_3/sr-core/plugins/storage/database"
	"gitee.com/linxing_3/sr-core/yerr"
	"gitee.com/mkwchecking/sr-admin/cmd"
	"gitee.com/mkwchecking/sr-admin/cmd/args"
	"gitee.com/mkwchecking/sr-admin/cmd/migrate/data"
	"github.com/spf13/cobra"

	_ "gitee.com/linxing_3/sr-core/plugins/storage/database/driver/sqlite3"
)

var (
	Migrate = &cobra.Command{
		Use:     "migrate [command] [flags]",
		Short:   "migrate data",
		Long:    "migrate [command] [flags]",
		Example: "migrate init -c ./config/config.yaml",
	}

	Init = &cobra.Command{
		Use:   "init data",
		Short: "migrate init [flags]",
		Long:  "migrate init [flags]",
		RunE: func(cmd *cobra.Command, args []string) error {
			return parseArgs(cmd, args)
		},
	}

	Args = struct {
		Config *args.ConfigArgs
	}{
		Config: &args.ConfigArgs{},
	}
)

func init() {
	Migrate.AddCommand(Init)
	cmd.RootCmd().AddCommand(Migrate)

	Args.Config.Parse(Init)
}

func parseArgs(cmd *cobra.Command, args []string) error {
	return StartUp(cmd.Context(), Args.Config)
}

func StartUp(ctx context.Context, args *args.ConfigArgs) error {
	cfg, err := app.SetupConfig(source.WithCfgFile(args.Config))
	if err != nil {
		return err
	}

	// setup db
	set, err := database.Install(cfg.Database, log.GetDefault())
	if err != nil {
		return err
	}

	// migrate
	db, ok := set.GetDefault()
	if !ok {
		return yerr.ErrBizPluginNotFound.Error("db not found")
	}

	if err = data.ResetMenuData(db); err != nil {
		return err
	}

	return nil
}
